<template>
  <!-- 创建地图容器 -->
  <div ref="map" style="height: 100%"></div>
</template>
<script>
import { get } from "@/utils/request";
import {mapMutations} from 'vuex';
export default {
  data() {
    return {
      //存放设备信息
      empData: [],
    };
  },
  methods: {
    ...mapMutations(['SET_ED']),
    //获取设备数据方法
    async getEmp() {
      let res = await get("/dashboard/findEngineerDeviceTree");
      // console.log(res, "获取响应");
      let temp = [];
      res.data.forEach((item) => {
        //item -->{id,name,chidlren}
        item.children.forEach((it) => {
          //it {id,name,position设备的信息}
          //push往数组里面添加东西
          temp.push(it);
        });
      });
      //console.log(temp,'设备数组');
      this.empData = temp;
      this.drawMap();
    },
    //绘制地图的方法
    drawMap() {
      //2.绘制地图
      var map = new AMap.Map(this.$refs.map, {
        zoom: 11, //缩放级别
        center: [103.842824,36.066535], //中心点坐标
        viewMode: "3D", //使用3D视图
        mapStyle: "amap://styles/graffti", //设置地图的显示样式
      });
      //动态生成标记点
      this.empData.forEach((item) => {
        //item -->{id,name,postion,}
        var marker = new AMap.Marker({
          position: item.position, //位置
          icon: "http://webapi.amap.com/theme/v1.3/markers/b/mark_bs.png",
          title: item.name,
          anchor: "bottom-left", // 设置锚点方位
          //标记点携带数据
          extData: item
        });
        //将组件实例赋值给vm变量
        let vm = this;
        marker.on("click", function () {
         
          //this --> 标记点组件实例
          vm.SET_ED({
            engineer_id:this.getExtData().engineer_id,
            device_id:this.getExtData().id
          })
          // console.log(this.getExeData(), "获取数据");
        });
        let polygons = [];
        var opts = {
          subdistrict: 0, //获取边界不需要返回下级行政区
          extensions: "all", //返回行政区边界坐标组等具体信息
          level: "district", //查询行政级别为 市
        };
        let district = new AMap.DistrictSearch(opts);
        district.setExtensions("all");
        district.search("兰州市", function (status, result) {
          map.remove(polygons); //清除上次结果
          polygons = [];
          var bounds = result.districtList[0].boundaries;
          if (bounds) {
            for (var i = 0, l = bounds.length; i < l; i++) {
              //生成行政区划polygon
              var polygon = new AMap.Polygon({
                strokeWeight: 5,
                path: bounds[i],
                fillOpacity: 0.4,
                fillColor: "#80d8ff",
                strokeColor: "#0091ea",
              });
              polygons.push(polygon);
            }
          }
          map.add(polygons);
          map.setFitView(polygons); //视口自适应
          map.add(marker);
        });
      });
    },
  },
  mounted() {
    //发送请求
    this.getEmp();
    // this.drawMap();
  },
};
</script>
<style>
.amap-icon img {
  width: 24px;
  height: 35px;
}
</style>